<template>
  <view style="padding-bottom: 100rpx;">
    <view class="homeBg h-44 relative">
      <view class="mt-5 flex justify-center items-center">
        <text class="text-white text-sm">账户余额（元）</text>
        <image class="w-5 h-5 ml-2" src="@/static/image/w-eye.png" @click="switchEye" v-if="isEyeFlag"></image>
        <image class="w-5 h-5 ml-2" src="@/static/image/w-noeye.png" @click="switchEye" v-else></image>
      </view>

      <view class="mt-2 text-center text-5xl text-white">{{ handleNumShow(userInfoData.userInfo.wallet, true) }}</view>

      <view class="mt-4 flex justify-center" v-if="!subAccountFlage">
        <view class="text-white text-center w-24 h-8 border border-solid rounded-2xl leading-8" @click="jumpWithdraw">提现
        </view>
      </view>

      <view class="logout top-2 right-4" @click="exit">
      </view>

    </view>

    <!--@click="jumpMineRevenue"-->
    <view class="h-10 px-2 flex justify-between items-center bg-gray-100" @click="jumpMineRevenue">
      <view class="flex items-center">
        <text class="text-sm text-slate-600">营收概况</text>
        <image class="w-4 h-4 ml-2" src="@/static/image/issue.png" @click.stop="openDrop"></image>
      </view>
      <view>
        <image class="w-4 h-4" src="@/static/image/rt.png"></image>
      </view>
    </view>

    <uiwu-popup v-model="popupValue">
      <view class="w-10/12 m-auto mt-28 rounded-xl bg-white p-4 box-border">
        <view class="text-center text-slate-600 text-sm relative">
          营收分成规则
          <image @click="popupValue = false" class="w-5 h-5 absolute top-0 right-0" src="@/static/image/close.png"></image>
        </view>
        <view class="flex mt-2">
          <view class="flex-1 text-slate-600 text-sm text-center">
            <view>营收范围</view>
            <view class="text-xs">(n&lt;X&lt;=m )</view>
          </view>
          <view class="flex-1 text-slate-600 text-sm flex items-center justify-center">分成</view>
        </view>
        <view class="mt-1" v-if="!subAccountFlage">
          <view class="flex py-1 bg-blue-100 rounded">
            <view class="flex-1 text-xs text-center">0 ~ 50000</view>
            <view class="flex-1 text-xs text-center">10%</view>
          </view>
          <view class="flex py-1 rounded">
            <view class="flex-1 text-xs text-center">50000 ~ 100000</view>
            <view class="flex-1 text-xs text-center">12%</view>
          </view>
          <view class="flex py-1 bg-blue-100 rounded">
            <view class="flex-1 text-xs text-center">100000以上</view>
            <view class="flex-1 text-xs text-center">15%</view>
          </view>
        </view>

        <view class="mt-1" v-else>
          <view class="rate-box">
            <!--configData.setInfo.rate  -->
            <view class="flex py-1 bg-blue-100 rounded" v-for="item in configData.setInfo.rate">
              <view class="flex-1 text-xs text-center">{{ item.start }} ~ {{ item.end }}</view>
              <view class="flex-1 text-xs text-center">{{ item.rate }}%</view>
            </view>
          </view>
        </view>

      </view>

    </uiwu-popup>

    <view class="h-28 flex bg-white">
      <view class="flex-1 overflow-hidden">
        <view class="text-xs text-center mt-4">本月待结算分成(元)</view>
        <view class="text-xs text-center my-1">总额: {{ revenueList.currentMonth.total }}元</view>
        <!--{{ revenueList.currentMonth.settle.toFixed() }}-->
        <view class="text-xs text-center my-1">(分成比 {{ (revenueList.currentMonth.settle * 100).toFixed() }}%)</view>
        <view class="text-sm text-center text-blue-600 font-bold flex items-center justify-center"><text>{{ handleNumShow(revenueList.currentMonth.money, true) }}</text></view>
      </view>

      <view class="flex-1">
        <view class="text-xs text-center mt-4">上月已结算分成(元)</view>
        <view class="text-xs text-center my-1">总额: {{ revenueList.lastMonth.total }}元</view>
        <!--{{ revenueList.currentMonth.settle }}-->
        <view class="text-xs text-center my-1">(分成比: {{ (revenueList.lastMonth.settle * 100).toFixed() }}%)</view>
        <view class="text-sm text-center text-blue-600 font-bold">{{ handleNumShow(revenueList.lastMonth.money, true) }}</view>
      </view>

      <view class="flex-1">
        <view class="text-xs text-center mt-4">历史总分成(元)</view>
        <view class="text-xs text-center my-1">总额: {{ revenueList.total.total }}元</view>
        <view class="text-xs text-center my-1">(分成比: {{ (revenueList.total.settle * 100).toFixed() }}%)</view>
        <view class="text-sm text-center text-blue-600 font-bold">{{ handleNumShow(revenueList.total.money, true) }}</view>
      </view>
    </view>

    <!--@click="jumpUser"-->
    <view @click="jumpUser">
      <view class="h-10 px-2 flex justify-between items-center bg-gray-100">
        <view>
          <text class="text-sm text-slate-600">用户概况</text>
        </view>
        <view>
          <image class="w-4 h-4" src="@/static/image/rt.png"></image>
        </view>
      </view>

      <view class="h-24 flex bg-white">
        <view class="flex-1 overflow-hidden">
          <view class="text-xs text-center text-blue-600 mt-4">昨日新增(人)</view>
          <view class="text-lg text-center text-blue-600 font-bold">{{ handleNumShow(userObject.yesterday, false) }}</view>
        </view>
        <view class="flex-1 overflow-hidden">
          <view class="text-xs text-center text-blue-600 mt-4">昨日充值(元)</view>
          <view class="text-lg text-center text-blue-600 font-bold">{{ handleNumShow(userObject.yesterday_recharge, false) }}</view>
        </view>
        <view class="flex-1 overflow-hidden">
          <view class="text-xs text-center text-blue-600 mt-4">总数(人)</view>
          <view class="text-lg text-center text-blue-600 font-bold">{{ handleNumShow(userObject.total, false) }}</view>
        </view>
      </view>

    </view>
    <view class="h-1 bg-gray-200"></view>

    <view class="px-4 pb-4">
      <view class="flex justify-between items-center py-2">
        <view class="text-sm text-slate-600">充值排行榜</view>
        <view class="w-2/4">
          <uni-data-select :clear="false" v-model="dateValue" :localdata="range" @change="dateChange"></uni-data-select>
        </view>
      </view>

      <view v-if="dateValue == 99">
        <uni-datetime-picker type="daterange" v-model="customTime" @change="customChange" :clear-icon="false"></uni-datetime-picker>
      </view>

      <view class="">
        <view v-if="loadStatus == 'loading'" class="m-auto mt-20">
          <uni-load-more :status="loadStatus" color="#d6d8d8"></uni-load-more>
        </view>

        <view v-else>
          <view v-if="rechargeList.length">
            <!--@scrolltolower="scrollMore"-->
            <scroll-view style="maxHeight: 400rpx" scroll-y>
              <view class="flex items-center my-2" v-for="item in rechargeList" :key="item.uid">
                <!--<image class="w-6 h-6" src="@/static/image/No_one.png"></image>-->
                <!--<view class="w-7 h-7 border border-solid rounded-full ml-4 mr-2"></view>-->
                <image :src="item.avatar" class="w-7 h-7 rounded-full ml-4 mr-2"></image>

                <view class="text-blue-600 text-xs">{{ item.nickname }} ({{ item.uid }})</view>
                <view class="flex ml-auto">
                  <view class="text-blue-600 text-xs">¥{{ item.total_amount }}</view>
                  <!--<view>-->
                  <!--  <image class="w-4 h-4 ml-10" src="@/static/image/rt.png"></image>-->
                  <!--</view>-->

                </view>
              </view>
            </scroll-view>
          </view>

          <view v-else>
            <image class="w-20 h-16 block m-auto mt-14" src="@/static/image/noData.png"></image>
            <view class="mt-2 text-center text-gray-400 text-sm">暂无数据</view>
          </view>
        </view>

      </view>

    </view>

  </view>

  <TabBar></TabBar>
</template>

<script setup lang="ts">
import moment from 'moment'
import { uiwu } from "@/api/interface/interface"
import { countFanApi, countsApi, rechargeListApi, countSettleApi } from '@/api/home/index'
import type { countSettleItf, countItf, rechargeListRequestItf, rechargeResultData } from '@/api/home/type'
import { ref, reactive, computed, onMounted } from 'vue'
import { userStore } from '@/store/userStore'
import { configStore } from '@/store/configStore'
import TabBar from '@/components/TabBar.vue'
import { onReady, onPullDownRefresh } from "@dcloudio/uni-app"

onReady(() => {
  uni.hideTabBar()
})

const configData = configStore()
const subAccountFlage = computed(() => {
  return userInfoData.userInfo.is_sub_account
})

/** 退出 **/
const userInfoData = userStore()
const exit = () => {
  uiwu.toast('退出成功')
  uni.removeStorageSync('token')
  uni.removeStorageSync('user')
  setTimeout(() => {
    uni.reLaunch({ url: '/pages/account/login' })
    userInfoData.clearUserInfo({})
  }, 2000)
}

/** 处理数字显示/隐藏 **/
const handleNumShow = (sum: any, isDecimal: boolean) => {
  // (sum as number).toFixed(2) return '￥' + Number(sum).toFixed(2)
  if (isEyeFlag.value) return isDecimal ? '￥' + Number(sum).toFixed(2) : sum;
  else return '*'
}

/** 营收概况 countSettleItf**/
const revenueList = ref<countSettleItf>({
  currentMonth: { money: '', total: 0, settle: 0 },
  lastMonth: { money: '', total: 0, settle: 0 },
  total: { money: '', total: 0, settle: 0 }
})

/** 用户概况 **/
const userObject = ref<countItf>({
  total: '',
  yesterday: '',
  yesterday_recharge: ''
})


onMounted(() => {
  pageRequest()
})

/** 页面重新请求 **/
const pageRequest = async () => {
  try {

    // 请求用户统计
    const res = await countsApi({ spread: userInfoData.userInfo.uid })
    userObject.value = res.data

    // 请求用户结算分成
    const rew = await countSettleApi()
    revenueList.value = rew.data

    // 请求充值排行榜
    dateChange(0)
  } catch (error) {
    // 如果有任何一个请求失败，则抛出错误
    throw error;
  }

}


const isEyeFlag = ref<boolean>(true)
const switchEye = () => {
  isEyeFlag.value = !isEyeFlag.value
}

const jumpWithdraw = () => {
  uni.navigateTo({ url: '/pages/withdraw/confirm' })
}

const popupValue = ref(false)
const openDrop = () => {
  popupValue.value = !popupValue.value
}

const jumpMineRevenue = () => {
  uni.navigateTo({ url: '/pages/mine/revenue' })
}

const jumpUser = () => {
  uni.navigateTo({ url: '/pages/mine/user' })
  // uni.navigateTo({ url: '/pages/fan/index' })
}

/** 充值排行榜 **/
const dateValue = ref<number>(0)
const dateParams:rechargeListRequestItf = reactive({
  start: '',
  end: '',
  page: 1,
  limit: 50
})

const range = reactive([
  { value: 0, text: '今日充值' },
  { value: 1, text: '昨日充值' },
  { value: 2, text: '最近7天' },
  { value: 3, text: '最近30天' },
  { value: 4, text: '历史总充值' },
  { value: 99, text: '自定义时间' },
])

const rechargeList = ref<rechargeResultData[]>([])
const loadStatus = ref<string>('loading') // 加载状态

/** 充值榜筛选条件  **/
const dateChange = async (value: number) => {
  // console.log(value.split)

  loadStatus.value = 'loading'
  let todayStart = moment().startOf('day')
  let nowTime = moment().format('YYYY-MM-DD HH:mm:ss') /** 现在时间 **/

  if(value == 0) {
    dateParams.start = todayStart.format('YYYY-MM-DD HH:mm:ss')
    dateParams.end = nowTime

  } else if (value == 1 ) {
    /** 昨天 **/
    let yesterDay = todayStart.subtract(1, 'days')
    dateParams.start = yesterDay.format('YYYY-MM-DD') + ' 00:00:00'
    dateParams.end = yesterDay.format('YYYY-MM-DD') + ' 23:59:59'
  } else if (value == 2) {
    /** 最近 7天 **/
    let sevenDay = todayStart.subtract(7, 'days')
    dateParams.start = sevenDay.format('YYYY-MM-DD') + ' 00:00:00'
    dateParams.end = nowTime
  } else if (value == 3 ) {
    /** 最近 30天 **/
    let thirthDay = todayStart.subtract(30, 'days')
    dateParams.start = thirthDay.format('YYYY-MM-DD') + ' 00:00:00'
    dateParams.end = nowTime
  } else if (value == 4 ) {
    /** 历史总充值 **/
    dateParams.start = ''
    dateParams.end = nowTime
  } else if (value == 99 ) {
    loadStatus.value = 'noMore'
    return
  }
  const res = await rechargeListApi(dateParams)
  rechargeList.value = res.data.data
  loadStatus.value = 'noMore'

}
/** 自定义时间 **/
const customTime = ref([])
const customChange = async() => {
  loadStatus.value = 'loading'
  dateParams.start = customTime.value[0]
  dateParams.end = customTime.value[1]
  const res = await rechargeListApi(dateParams)
  rechargeList.value = res.data.data
  loadStatus.value = 'noMore'
}
/** end **/

/** 滚动加载更多 **/
// const scrollMore =


/** 下拉刷新 **/
onPullDownRefresh( () => {
  pageRequest().then(() => {
    userInfoData.updateUserInfo()
    configData.initInfoData()
    uni.stopPullDownRefresh();
  })
})
</script>

<style scoped lang="scss">
image {
  display: block;
}

.homeBg {
  background: url("@/static/image/homeBg.png") no-repeat;
  background-size: cover;
  overflow: hidden;

  .logout {
    position: absolute;
    width: 80rpx;
    height: 100rpx;
    background: url("@/static/image/logout.png") no-repeat;
    background-size: cover;
  }
}

.rate-box {
  max-height: 300rpx;
  overflow-y: auto;
  &>view:nth-child(2n) {
    background: #Fff;
  }
}
</style>
